package com.cool.cloud.service.impl;

import com.cool.cloud.entity.BGWork;
import com.cool.cloud.entity.MyFile;
import com.cool.cloud.service.BGWorkService;
import com.cool.cloud.service.MyFileService;
import com.cool.cloud.utils.FileTypeUtil;
import com.cool.cloud.utils.FtpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class BGWorkServiceImpl extends BaseService implements BGWorkService {
    @Autowired
    MyFileService myFileService;
    @Autowired
    FileStoreServiceImpl fileStoreService;

    @Override
    public int insert(BGWork bgwork) {
        return bgWorkMapper.insert(bgwork);
    }

    @Override
    public List<BGWork> queryByUserId(Integer userid) {
        return bgWorkMapper.queryByUserId(userid);
    }

    @Override
    public int update(BGWork bgwork) {
        return bgWorkMapper.update(bgwork);
    }

    @Override
    public int batchDelete(String[] pks) {
        return bgWorkMapper.batchDelete(pks);
    }

    @Override
    @Async
    public void excute(BGWork bgwork, Integer sec, Integer folderid, Integer storeid) throws Exception {
        try {
            TimeUnit.MINUTES.sleep(sec);
        } catch (InterruptedException e) {
            throw new InterruptedException(e.getMessage());
        }
        //java执行http下载、创建文件、更新仓库容量
        if (Download(bgwork.getCreateUserid(), bgwork.getDlUrl(), folderid, storeid)) {
            //看执行结果更新bgwork对象
            bgwork.setStatus(1);
            bgWorkMapper.update(bgwork);
        } else {
            bgwork.setStatus(2);
            bgWorkMapper.update(bgwork);
        }
    }

    /**
     * java执行http下载、创建文件、更新仓库容量
     */
    private boolean Download(Integer userid, String url, Integer folderid, Integer storeid) {
        String size = String.valueOf(getFileLength(url) / 1024.0);
        String path = "";
        String fileName = "";
        String postfix = "";
        Integer type = 5;
        try {
            URL Url = new URL(url);
            //通过远程url连接对象打开一个连接，强转成HTTPURLConnection类
            HttpURLConnection conn = (HttpURLConnection) Url.openConnection();
            conn.setRequestMethod("GET");
            //设置连接超时时间和读取超时时间
            conn.setConnectTimeout(15000);
            conn.setReadTimeout(60000);
            conn.setRequestProperty("Accept", "*/*");
            fileName = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf("."));
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String dateStr = format.format(new Date());
            path = userid + "/" + dateStr + "/" + folderid;
            postfix = url.substring(url.lastIndexOf("."));
            type = FileTypeUtil.getType(postfix.toLowerCase());

            //发送请求
            conn.connect();

            //通过conn取得输入流，并使用Reader读取
            if (200 == conn.getResponseCode()) {
                InputStream is = conn.getInputStream();
                int indexDot = size.lastIndexOf(".");
                size = size.substring(0, indexDot);
                if (FtpUtil.uploadFile(path, fileName + postfix, is)) {
                    myFileService.addFileByFileStoreId(
                            MyFile.builder()
                                    .myFileName(fileName).fileStoreId(storeid).myFilePath(path)
                                    .downloadTime(0).uploadTime(new Date()).parentFolderId(folderid).
                                    size(Integer.valueOf(size)).type(type).postfix(postfix).build());
                    //更新仓库表的当前大小
                    fileStoreService.addSize(storeid, Integer.valueOf(size));
                } else {
                    return false;
                    //上传失败
                }
            } else {
                return false;
                //下载失败
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }


    /**
     * 获取网络文件大小
     */
    private static long getFileLength(String downloadUrl) {
        if (downloadUrl == null || "".equals(downloadUrl)) {
            return 0L;
        }
        URL url = null;
        try {
            url = new URL(downloadUrl);
        } catch (MalformedURLException e) {
            return 0L;
        }
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("HEAD");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows 7; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36 YNoteCef/5.8.0.1 (Windows)");
            return (long) conn.getContentLength();
        } catch (Exception e) {
            return 0L;
        } finally {
            conn.disconnect();
        }
    }

}
